/**
* 机器人监控页面
* 功能：使用robot_status_client和map_download_action_client基于ROS2 Service和Action实现SRC2000机器人地图下载功能；
* 注释：ROS2底层DDS默认限制传输数据大小，实测数据报超过256KB都会被截断，因此地图数据传输时请勿超过256KB，但是实测即使分块传输数据包为256KB则DDS概率性丢包；
*/
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls.Material 2.15
import QtGraphicalEffects 1.15
import "../components" 1.0
import "../pages" 1.0  // 导入地图视图组件

Page {
    id: monitorPage
    property string robotId: ""
    property string seerIP: ""
    property string cameraUrl: ""
    property var stackView: null
    //SRC2000电池、位置、导航状态
    property var batteryValue: "85%"
    property var positionValueX: "0.0"
    property var positionValueY: "0.0"
    property var statusValue: "未知"
    property var statusColor: "green"

    //传感器数据属性
    property string airTemperature: "24.5℃"
    property string airHumidity: "65%"
    property string lightIntensity: "850 lux"
    property string co2Concentration: "450 ppm"
    property string soilTemperature: "22.3℃"
    property string soilMoisture: "42%"

    signal requestBack()

    Connections {
        target: heartbeatModel
        function onRobotStatusUpdated(robotId, status, currentTarget, battery, x, y) {
            // 检查机器人ID
            if (robotId === monitorPage.robotId) {
                // 更新电池信息
                batteryValue = (battery > 0) ? battery + "%" : "N/A"

                // 更新位置信息
                positionValueX = x.toFixed(2)
                positionValueY = y.toFixed(2)

                // 更新导航状态
                statusValue = status + (currentTarget ? "→" + currentTarget : "")
                statusColor = status === "RUNNING" ? "#4CAF50" :
                             status === "FAILED" ? "#F44336" : "#FFC107"
            }
        }
    }

    // 连接机器人状态客户端的地图名称更新信号
    Connections {
        target: robotStatusClient
        function onMapNameUpdated(mapName) {
            if (mapName.length > 0) {
                // 检查本地是否存在该地图
                var mapFileName = mapName;
                if (!mapFileName.endsWith(".smap")) {
                    mapFileName += ".smap";
                }
                var mapFilePath = "resource/" + monitorPage.robotId + "/map/" + mapFileName;
                
                // 使用Qt.fileExists检查文件是否存在（这需要在C++端实现）
                if (!robotStatusClient.isFileExists(mapFilePath)) {
                    console.log("地图文件不存在，开始下载 - 地图: " + mapName);
                    // 调用地图下载功能（这需要在C++端实现）
                    robotStatusClient.downloadMap(monitorPage.robotId, mapName);
                } else {
                    console.log("地图文件已存在 - 地图: " + mapName);
                }
            }
        }
        
        function onQueryFailed(error) {
            console.log("查询地图名称失败: " + error);
        }
    }

    // 连接传感器数据更新信号
    Connections {
        target: sensorSubscriber
        function onSensorDataUpdated(robotId, airTemperature, airHumidity, lightIntensity,
                                    co2Concentration, soilTemperature, soilMoisture) {
            /*
            console.log("QML接收到传感器数据，来自机器人:", robotId)
            console.log("  空气温度:", airTemperature)
            console.log("  空气湿度:", airHumidity)
            console.log("  光照强度:", lightIntensity)
            console.log("  CO2浓度:", co2Concentration)
            console.log("  土壤温度:", soilTemperature)
            console.log("  土壤湿度:", soilMoisture)
            */
            // 检查是否是我们关注的机器人
            if (robotId === monitorPage.robotId) {
                // 更新属性
                monitorPage.airTemperature = airTemperature
                monitorPage.airHumidity = airHumidity
                monitorPage.lightIntensity = lightIntensity
                monitorPage.co2Concentration = co2Concentration
                //monitorPage.soilTemperature = soilTemperature
                //monitorPage.soilMoisture = soilMoisture
            } else {
                console.log("收到其他机器人的数据，忽略:", robotId)
            }
        }
    }
    /*
    Connections {
        target: robotController
        function onBatteryUpdated(level) {
            batteryValue = (level > 0) ? (level * 100).toFixed(0) + "%" : "N/A"
        }
    }

    Connections {
        target: robotController
        function onPositionUpdated(x, y, angle) {
            positionValueX = x.toFixed(2)
            positionValueY = y.toFixed(2)
            //compass.rotation = angle // 直接控制指南针控件
        }
    }

    Connections {
        target: robotController
        function onNavigationStateUpdated(state, target) {
            statusValue = state + (target ? "→" + target : "")
            statusColor = state === "RUNNING" ? "#4CAF50" :
                         state === "FAILED" ? "#F44336" : "#FFC107"
        }
    }
    */
    Component.onCompleted: {
        console.log("----> seerIP: " + seerIP + ", cameraUrl: " + cameraUrl);
        Qt.callLater(function() {
            robotStatusClient.queryMapName(monitorPage.robotId);
        });
        /*
        if (monitorPage.seerIP) {
            robotController.connectRobot(monitorPage.seerIP)    // 连接SRC2000
            robotController.setParameters(monitorPage.robotId)     // 设置robotId以备下载map资源到对应robot目录等
            console.log("Connecting robot at:", monitorPage.seerIP)
            // 异步查询地图名称
            robotStatusClient.queryMapName(monitorPage.robotId);
        } else {
            console.warn("seerIP is empty!")
        }
        */
    }

    Component.onDestruction:{
         /*
         if (typeof robotController !== "undefined" && robotController) {
                    robotController.disconnectRobot()  //断开SRC2000连接
        }
        */
    }
    

    // ===== 顶部导航工具栏 =====
    header: ToolBar {
        id: navBar
        property int currentIndex: 0  // 默认选中"机器监控"
        Material.background: Material.color(Material.Grey, Material.Shade100)
        Material.elevation: 4
        layer.enabled: true
        layer.effect: DropShadow {
            color: "#40000000"
            radius: 8
            samples: 16
            verticalOffset: 2
        }

        RowLayout {
            anchors.fill: parent
            spacing: 0

            // 返回按钮（左侧）
            ToolButton {
                icon.source: "qrc:///icons/back.svg"
                icon.color: Material.foreground
                onClicked: {
                    if (stackView) stackView.pop()
                    else if (StackView.view) StackView.view.pop()
                    else requestBack()
                }
            }

            // 导航选项（居中）
            Repeater {
                model: ["机器监控", "地图视图", "任务链条","机器状态"]
                delegate: Button {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 38
                    Layout.maximumWidth: 180

                    background: Rectangle {
                        radius: 4
                        color: navBar.currentIndex === index ?
                               Material.accent : Material.background
                        border.color: Material.color(Material.Grey, Material.Shade300)

                        layer.enabled: navBar.currentIndex === index
                        layer.effect: DropShadow {
                            color: "#20000000"
                            radius: 6
                            samples: 12
                        }
                    }

                    contentItem: Text {
                        text: modelData
                        horizontalAlignment: Text.AlignHCenter
                        color: navBar.currentIndex === index ?
                               "white" : Material.color(Material.Grey, Material.Shade800)
                        font.bold: navBar.currentIndex === index
                    }

                    onClicked: {
                        navBar.currentIndex = index
                        if (index === 0) innerStackView.replace(monitorContent)
                        else if (index === 1) innerStackView.replace(mapViewerPage)
                        else if (index === 2) innerStackView.replace(taskChainPage)
                        else if (index === 3) innerStackView.replace(robotStatusPage)
                    }
                }
            }

            // 空白区域填充（右侧）
            Item { Layout.fillWidth: true }
        }
    }

    // ===== 页面内容区域 =====
    StackView {
        id: innerStackView
        anchors.fill: parent
        anchors.margins: 15
        // 初始页面延迟加载
        Component.onCompleted: replace(monitorContent)

        // 页面切换动画
        pushEnter: Transition {
            PropertyAnimation {
                property: "opacity"
                from: 0
                to: 1
                duration: 300
            }
        }
        popExit: Transition {
            PropertyAnimation {
                property: "opacity"
                from: 1
                to: 0
                duration: 300
            }
        }
    }

    // ===== 页面组件定义 =====
    Component {
        id: monitorContent

        GridLayout {
            width: innerStackView.width
            height: innerStackView.height
            anchors.margins: 15   // 保留边距
            columns: 2
            columnSpacing: 20
            rowSpacing: 20

            // === 区域1：摄像头控制 ===
            Rectangle {
                id: cameraArea
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.columnSpan: 1
                radius: 12
                color: "#21252B"
                clip: true

                // 摄像头预览占位符
                Rectangle {
                    id: cameraPlaceholder
                    anchors.fill: parent
                    anchors.margins: 10
                    color: "#2C313A"
                    radius: 8
                    visible: !cameraLoader.active

                    Column {
                        anchors.centerIn: parent
                        spacing: 20

                        Image {
                            source: "qrc:///icons/camera.png"
                            anchors.horizontalCenter: parent.horizontalCenter
                            width: 80
                            height: 80
                        }

                        Text {
                            text: "点击开启摄像头预览"
                            color: "#ABB2BF"
                            font.pixelSize: 18
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            cameraLoader.active = true
                            if (cameraLoader.item) {
                                cameraLoader.item.initCamera()
                            }
                            mouse.accepted = false
                        }
                        propagateComposedEvents: true
                    }
                }

                // 摄像头加载器
                Loader {
                    id: cameraLoader
                    anchors.fill: parent
                    active: false
                    sourceComponent: HiKCameraControl {
                        id: cameraControl
                        anchors.fill: parent
                        robotId: monitorPage.robotId
                        cameraUrl: monitorPage.cameraUrl
                    }
                }
            }

            // === 区域2：传感器数据 ===
            Rectangle {
                id: sensorArea
                Layout.fillWidth: true
                Layout.fillHeight: true
                radius: 12
                color: "#21252B"

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 15
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    spacing: 10

                    Text {
                        text: "环境传感器数据"
                        color: "white"
                        font.bold: true
                        font.pixelSize: 18
                        Layout.alignment: Qt.AlignHCenter
                    }

                    // 传感器网格
                    GridLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        columns: 2
                        rowSpacing: 15
                        columnSpacing: 20

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "空气温度"
                            value: monitorPage.airTemperature
                            icon: "qrc:/icons/temp.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "空气湿度"
                            value: monitorPage.airHumidity
                            icon: "qrc:/icons/humidity.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "光照强度"
                            value: monitorPage.lightIntensity
                            icon: "qrc:/icons/light.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "CO₂浓度"
                            value: monitorPage.co2Concentration
                            icon: "qrc:/icons/co2.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "土壤温度"
                            value: monitorPage.soilTemperature
                            icon: "qrc:/icons/soil-temp.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "土壤湿度"
                            value: monitorPage.soilMoisture
                            icon: "qrc:/icons/soil-moisture.png"
                        }
                    }
                }
            }

            // === 区域3：状态信息 ===
            Rectangle {
                id: statusArea
                Layout.fillWidth: true
                Layout.preferredHeight: 150
                radius: 12
                color: "#21252B"

                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 15
                    spacing: 20

                    StatusIndicator {
                        title: "电量"
                        value: batteryValue
                        icon: "qrc:/icons/battery.png"
                        progress: batteryValue ? parseFloat(batteryValue) / 100.0 : 0.85
                        property double batteryLevel: batteryValue ? parseFloat(batteryValue) : 85
                        statusColor: batteryLevel < 20 ? "#F44336" : "#4CAF50"
                    }

                    StatusIndicator {
                        title: "位置"
                        value: "X: " + positionValueX + " Y: " + positionValueY
                        icon: "qrc:/icons/location.png"
                    }

                    StatusIndicator {
                        title: "导航状态"
                        value: statusValue
                        icon: "qrc:/icons/status.png"
                        statusColor: statusColor
                    }
                }
            }

            // === 区域4：任务创建 ===
            Rectangle {
                id: taskArea
                Layout.fillWidth: true
                Layout.preferredHeight: 150
                radius: 12
                color: "#21252B"

                Button {
                    id: createTaskButton
                    icon.source: "qrc:///icons/add-task.png"
                    icon.color: "white"

                    contentItem: Row {
                        spacing: 10
                        Image {
                            source: createTaskButton.icon.source
                            width: 24
                            height: 24
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        Text {
                            text: "创建新任务"
                            color: "green"
                            font.pixelSize: 16
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }

                    onClicked: taskDialog.open()
                }
            }
        }
    }

    // === 地图视图组件 ===
    Component {
        id: mapViewerPage
        MapViewerPage {
            width: innerStackView.width
            height: innerStackView.height
            robotId: monitorPage.robotId
            //currentMapName: robotController.getCurrentMapName()
        }

    }

    // === 任务链条组件 ===
    Component {
        id: taskChainPage
        TaskChainPage {
            width: innerStackView.width
            height: innerStackView.height
        }
    }

    // === 状态组件(占位) ===
    Component {
        id: robotStatusPage
        Label {
            text: "状态(暂未实现)"
            color: "black"
            font.bold: true
            font.pixelSize: 18
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
            anchors.fill: parent
        }
    }
    // ===== 任务创建对话框 =====
    Dialog {
        id: taskDialog
        title: "创建新任务"
        modal: true
        standardButtons: Dialog.Ok | Dialog.Cancel
        anchors.centerIn: parent
        width: 400

        ColumnLayout {
            anchors.fill: parent
            spacing: 15

            TextField {
                placeholderText: "任务名称"
                Layout.fillWidth: true
            }

            ComboBox {
                model: ["巡检任务", "除草任务", "采摘任务", "运输任务","嫁接任务","讲解任务"]
                Layout.fillWidth: true
            }

            GridLayout {
                columns: 2
                rowSpacing: 10
                columnSpacing: 15

                Text { text: "开始时间:"; color: "white" }
                TextField { Layout.fillWidth: true }

                Text { text: "持续时间:"; color: "white" }
                TextField { Layout.fillWidth: true }

                Text { text: "目标区域:"; color: "white" }
                TextField { Layout.fillWidth: true }
            }
        }
    }
}
